package org.kzwl.service.web.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.advice.Consts;
import org.kzwl.comm.pojo.ResponseData;
import org.kzwl.comm.pojo.bo.QueryAdminCuVenuesBO;
import org.kzwl.comm.pojo.bo.SaveCuVenuesBO;
import org.kzwl.comm.pojo.bo.venues.QueryDetailsBO;
import org.kzwl.comm.pojo.bo.venues.VenueBasicBO;
import org.kzwl.comm.pojo.dto.CuVenuesUserDTO;
import org.kzwl.comm.pojo.dto.venues.QueryRecordDTO;
import org.kzwl.comm.pojo.dto.venues.VenuesBasicDTO;
import org.kzwl.comm.pojo.dto.venues.VenuesDetailsDTO;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.entity.app.User;
import org.kzwl.entity.web.CuVenues;
import org.kzwl.entity.web.CuVenuesUser;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.mapper.web.CuVenuesMapper;
import org.kzwl.mapper.web.CuVolunteersMapper;
import org.kzwl.mapper.web.VenuesUserMapper;
import org.kzwl.service.web.CuVenuesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 场馆预约 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-12-18
 */
@Service
public class CuVenuesServiceImpl extends ServiceImpl<CuVenuesMapper, CuVenues> implements CuVenuesService {

    @Autowired
    private CuVenuesMapper venuesMapper;

    @Autowired
    private VenuesUserMapper venuesUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseData<Void> saveOne(SaveCuVenuesBO saveCuVenuesBO) {
        CuVenues cuVenues = new CuVenues();
        BeanUtils.copyProperties(saveCuVenuesBO, cuVenues);
        this.baseMapper.insert(cuVenues);
        return new ResponseData<>();
    }

    @Override
    public ResponseData<IPage<CuVenues>> queryPages(QueryAdminCuVenuesBO queryAdminCuVenuesBO) {

        QueryWrapper<CuVenues> cuVenuesQueryWrapper = new QueryWrapper<>();
        cuVenuesQueryWrapper
                .lambda()
                .eq(queryAdminCuVenuesBO.getCuVenuesIs() != null, CuVenues::getCuVenuesIs, queryAdminCuVenuesBO.getCuVenuesIs())
                .like(!"".equals(queryAdminCuVenuesBO.getCuVenuesTitle()), CuVenues::getCuVenuesTitle, queryAdminCuVenuesBO.getCuVenuesTitle());
        Page<CuVenues> cuVenuesPage = this.baseMapper.selectPage(new Page<>(queryAdminCuVenuesBO.getCurrent(), queryAdminCuVenuesBO.getSize()), cuVenuesQueryWrapper);
        return new ResponseData<>(cuVenuesPage);
    }

    @Override
    public ResponseData<CuVenues> queryOne(Long Id) {
        if (ObjectUtil.isNull(this.baseMapper.selectById(Id))) {
            throw new BizException("查无此信息");
        }
        return new ResponseData<>(this.baseMapper.selectById(Id));
    }

    @Override
    public ResponseData<Void> updateOne(SaveCuVenuesBO saveCuVenuesBO) {
        if (ObjectUtil.isNull(this.baseMapper.selectById(saveCuVenuesBO.getCuVenuesId()))) {
            throw new BizException("查无此信息");
        }
        CuVenues cuVenues = new CuVenues();
        BeanUtils.copyProperties(saveCuVenuesBO, cuVenues);
        this.updateById(cuVenues);

        return new ResponseData<>();
    }

    @Override
    public ResponseData<Void> deleteId(Long Id) {
        CuVenues cuVenues = this.baseMapper.selectById(Id);
        if (ObjectUtil.isNull(cuVenues)) {
            throw new BizException("查无此信息");
        } else if (cuVenues.getCuVenuesAlreadyIs() == 0) {
            throw new BizException("此场馆已被预约,无法删除");
        }

        this.baseMapper.deleteById(Id);
        return new ResponseData<>();
    }

    //region 场馆预约基础查询
    @Override
    public IPage<VenuesBasicDTO> queryBasic(VenueBasicBO bo) {
        QueryWrapper<CuVenues> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().apply("cu_venues_num < cu_venues_people_number").gt(CuVenues::getCuVenuesEndDate,LocalDateTime.now()).orderByDesc(CuVenues::getCuVenuesOpenDate);
        IPage<CuVenues> page = new Page<>();
        page.setCurrent(bo.getCurrent());
        page.setSize(bo.getSize());
        page = venuesMapper.selectPage(page, queryWrapper);
        IPage<VenuesBasicDTO> answer = new Page<>();
        BeanUtils.copyProperties(page, answer);
        List<VenuesBasicDTO> cuVenues = JSONObject.parseArray(JSONObject.toJSONString(page.getRecords()), VenuesBasicDTO.class);
        cuVenues.forEach(l->{
            l.getCuVenuesImgList().addAll(JSONObject.parseArray(l.getCuVenuesImg(), String.class));
            l.setCuVenuesImg(l.getCuVenuesImgList().get(0));
        });
        answer.setRecords(cuVenues);
        return answer;
    }
    //endregion

    //region 查询场馆预约详细
    @Override
    public VenuesDetailsDTO queryDetails(QueryDetailsBO bo) {
        CuVenues cuVenues = venuesMapper.selectById(bo.getCuVenuesId());
        if (cuVenues == null) {
            throw new BizException("未查询到相关信息");
        }
        VenuesDetailsDTO dto = new VenuesDetailsDTO();
        BeanUtils.copyProperties(cuVenues, dto);
        if (bo.getCuUserId() != 0 && bo.getCuUserId() != null) {
            QueryWrapper<CuVenuesUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CuVenuesUser::getCuUserId, bo.getCuUserId()).eq(CuVenuesUser::getCuVenuesId, bo.getCuVenuesId());
            Integer integer = venuesUserMapper.selectCount(queryWrapper);
            if (integer > 0) {
                dto.setIsJoin(1);
            }
        }
        return dto;
    }
    //endregion

    //region 参与场馆预约
    @Transactional
    @Override
    public void joinVenues(QueryDetailsBO bo) {
        CuVenues cuVenues = venuesMapper.selectById(bo.getCuVenuesId());
        if (!cuVenues.getCuVenuesEndDate().isAfter(LocalDateTime.now())) {
            throw new BizException("活动已结束");
        }

        if (cuVenues.getCuVenuesNum()>=cuVenues.getCuVenuesPeopleNumber()){
            throw new BizException("人数已满");
        }

        QueryWrapper<CuVenuesUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CuVenuesUser::getCuUserId, bo.getCuUserId()).eq(CuVenuesUser::getCuVenuesId, bo.getCuVenuesId());
        Integer integer = venuesUserMapper.selectCount(queryWrapper);
        if (integer > 0) {
            throw new BizException("您已参与");
        }
        CuVenuesUser venuesUser = new CuVenuesUser();
        venuesUser.setCuUserId(bo.getCuUserId());
        venuesUser.setCuVenuesId(bo.getCuVenuesId());
        venuesUserMapper.insert(venuesUser);
        venuesMapper.syncNum(bo.getCuVenuesId());
        User user = userMapper.selectById(bo.getCuUserId());
        String param = "{" +
                "\"name\":\"" + user.getCuUsername() + "\"," +
                "\"title\":\"" + cuVenues.getCuVenuesTitle() +"\"," +
                "\"time\":\""+cuVenues.getCuVenuesOpenDate().toString().replace("T"," ")+"\"" +
                "}";
        System.out.println(param);
        MyUtils.sendSms(user.getCuUserPhone(),param
                , Consts.AliYun.SMSVENUES);
    }
    //endregion

    //region 场馆预约参与记录
    @Override
    public QueryRecordDTO queryRecord(QueryDetailsBO bo) {
        QueryRecordDTO dto = new QueryRecordDTO();
        List<VenuesBasicDTO> venuesBasicDTOS = venuesUserMapper.queryRecord(bo);
        venuesBasicDTOS.forEach(l->{
            if (l.getCuVenuesEndDate().isAfter(LocalDateTime.now())){
                dto.getNow().add(l);
            }else{
                dto.getOld().add(l);
            }
        });
        return dto;
    }
    //endregion


    @Override
    public ResponseData<List<CuVenuesUserDTO>> queryVenuesUser(Integer cuVenuesId) {
        List<CuVenuesUserDTO> dtoList = new ArrayList<>();
        List<CuVenuesUser> venuesUsers = this.venuesUserMapper.selectList(new LambdaQueryWrapper<CuVenuesUser>().eq(CuVenuesUser::getCuVenuesId, cuVenuesId));
        if (venuesUsers.size() != 0){
            venuesUsers.forEach(item ->{
                CuVenuesUserDTO cuVenuesUserDTO = new CuVenuesUserDTO();
                User user = this.userMapper.selectById(item.getCuUserId());
                cuVenuesUserDTO.setCuUsername(user.getCuUsername());
                cuVenuesUserDTO.setCuVenuesCreateDate(item.getCuVenuesCreateDate());
                cuVenuesUserDTO.setCuUserId(item.getCuUserId());
                dtoList.add(cuVenuesUserDTO);
            });
        }
        return new ResponseData<>(dtoList);
    }
}
